package com.jeesite.modules.exam.socreResult.service;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.exam.assessment.entity.DcSupExamInfo;
import com.jeesite.modules.exam.quota.entity.DcSupExamQuotaAdd;
import com.jeesite.modules.exam.quota.entity.DcSupExamSumQuotaInfo;
import com.jeesite.modules.exam.quota.service.DcSupExamQuotaOrgService;
import com.jeesite.modules.exam.quota.service.DcSupExamSumQuotaInfoService;
import com.jeesite.modules.exam.quota.service.DcSupExamSumQuotaService;
import com.jeesite.modules.exam.score.dao.DcSupExamSumScoreDao;
import com.jeesite.modules.exam.score.entity.DcSupExamScore;
import com.jeesite.modules.exam.score.entity.DcSupExamSumScore;
import com.jeesite.modules.exam.socreResult.dao.DcSupExamSumScoreResultDao;
import com.jeesite.modules.exam.socreResult.dto.CheckIndexDataDto;
import com.jeesite.modules.exam.socreResult.dto.ExamUnitNameDto;
import com.jeesite.modules.msg.entity.MsgPush;
import com.jeesite.modules.msg.send.SmsSendService;
import com.jeesite.modules.msg.service.MsgInnerService;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.utils.DictUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 评分结果查看相关实现
 *
 * @author wangjie
 * @date 2022-06-02
 */
@Service
public class DcSupExamSumScoreResultService extends CrudService<DcSupExamSumScoreDao, DcSupExamSumScore> {
    @Autowired
    private DcSupExamSumScoreResultDao dcSupExamSumScoreResultDao;

    @Autowired
    private DcSupExamSumQuotaService dcSupExamSumQuotaService;
    @Autowired
    private DcSupExamQuotaOrgService dcSupExamQuotaOrgService;

    @Autowired
    SmsSendService smsSendService;

    @Autowired
    MsgInnerService msgInnerService;
    @Autowired
    private  DcSupExamSumScoreDao dcSupExamSumScoreService;

    private DcSupExamSumQuotaInfoService dcSupExamSumQuotaInfoService;
    /**
     * 评分结果列表查询
     *
     * @return
     */
    public Page<DcSupExamInfo> listData(DcSupExamInfo dcSupExamInfo) {
        List<DcSupExamInfo> list = dcSupExamSumScoreResultDao.listData(dcSupExamInfo);
        dcSupExamInfo.getPage().setCount(list.size());
        return dcSupExamInfo.getPage().setList(list);
    }

    /**
     * 查找考核任务中的考核单位
     *
     * @param examId   考核任务id
     * @param unitName 考核单位名称
     * @return
     */
    public Page<ExamUnitNameDto> queryUnits(String examId, String unitName,String type, HttpServletRequest request, HttpServletResponse response) {

        ExamUnitNameDto examUnitNameDto = new ExamUnitNameDto();

        examUnitNameDto.setPage(new Page<>(request, response));
        examUnitNameDto.setExamId(examId);
        examUnitNameDto.setExameOrgName(unitName);

        List<ExamUnitNameDto> list = dcSupExamSumScoreResultDao.queryUnits(examUnitNameDto);
        if (!CollectionUtils.isEmpty(list)){
            // 查询机构单位是否评分
           Set<String> mapList =  dcSupExamSumScoreResultDao.queryIsQuotaScore(examId);
            if (!CollectionUtils.isEmpty(mapList)){
                list.forEach(s->{
                     String org = s.getExameOrg();
                    if (mapList.contains(org)){
                        s.setScoreType("9");
                    }else{
                        s.setScoreType("0");
                    }
                });
            }
        }

        return examUnitNameDto.getPage().setList(list);
    }

    /**
     * 考核结果数据 列表数据查询
     *
     * @param orgCode
     * @param examId
     * @param year
     * @param request
     * @param response
     * @return
     */
    @Deprecated
    public Page<CheckIndexDataDto> resultCheckData(String orgCode, String examId, String year, String version, HttpServletRequest request, HttpServletResponse response) {
        CheckIndexDataDto resultCheckDataDto = new CheckIndexDataDto();
        Page<Object> page = new Page<>(request, response);
//        List<ResultCheckDataDto> result = dcSupExamSumScoreResultDao.resultCheckData(orgCode, examId, year, version);
        List<CheckIndexDataDto> result = queryExamSumScore(examId, year, orgCode,"single");
        List<CheckIndexDataDto> addAndSub = queryExamSumScore(examId, year, orgCode,"addAndSub");
        resultCheckDataDto.setPage(page);
        return resultCheckDataDto.getPage().setList(result);
    }

    /**
     * 查询考核自评页面数据信息
     *
     * @param examId 考核任务id
     * @param year   考核年份
     * @return
     */
    public Map<String, String> checkInfo(String examId, String year, String orgCode) {
        return dcSupExamSumScoreResultDao.checkInfo(examId, year,orgCode);
    }

    /**
     * 考核自评页面指标数据列表
     *
     * @param examId   考核任务id
     * @param year     考核年份
     * @param orgCode  考核机构代码
     * @param request
     * @param response
     * @return
     */
    public Page<CheckIndexDataDto> checkIndexData(String examId, String year, String orgCode, HttpServletRequest request, HttpServletResponse response) {
        // 查询 考核任务指标评分表-主表  是否有记录 dc_sup_exam_score 考核任务指标评分表-主表
        List<DcSupExamScore> dcSupExamScore= dcSupExamSumScoreResultDao.validationExist(examId,year,orgCode);
        if (dcSupExamScore == null){
            return null;
        }
        CheckIndexDataDto checkIndexDataDto = new CheckIndexDataDto();
        Page<CheckIndexDataDto> page = new Page<>(request, response);
        // 查询 考核任务指标评分表-主表 与 考核任务指标评分表-打分信息 得到  考核任务评分汇总表  指标id
        List<CheckIndexDataDto> result = dcSupExamSumScoreResultDao.checkIndexData(examId, year, orgCode);
        checkIndexDataDto.setPage(page);
        return checkIndexDataDto.getPage().setList(result);
    }

    /**
     * 查询 考核任务指标评分表-主表 与 考核任务指标评分表-打分信息 得到  考核任务评分汇总表(指标id、评分来源（1汇总指标、2加减分项))
     *
     * @param examId  考核任务id
     * @param year    考核年份
     * @param orgCode 考核机构代码
     * @return 考核自评指标列表
     */
    public List queryExamSumScore(String examId, String year, String orgCode,String type) {
        // 考核结果   关键指标  单项指标  加减分指标
        // 1、关键指标  单项指标  查询  dc_sup_exam_sum_score
//        List<CheckIndexDataDto> scoreList = dcSupExamSumScoreResultDao.queryExamSumScore(examId, year, orgCode);
//        if (CollectionUtils.isEmpty(scoreList)){
//            scoreList =new ArrayList<>();
//        }
//        // 2、加减分指标 dc_sup_exam_sum_score  dc_sup_exam_quota_add
//        List<CheckIndexDataDto> addAndSubDatas=dcSupExamSumScoreResultDao.examAddAndSubSumScore(examId, year, orgCode);
//        if (!CollectionUtils.isEmpty(addAndSubDatas)){
//            scoreList.addAll(addAndSubDatas);
//        }
        // 关键 + 单项
        if ("single".equals(type)){
        List<DcSupExamSumQuotaInfo>  result = dcSupExamSumScoreResultDao.queryExamSumScore(examId, year, orgCode);
        return  result;
            // 加减分指标
        }else{
            List<DcSupExamQuotaAdd>   result=dcSupExamSumScoreResultDao.examAddAndSubSumScore(examId, year, orgCode);
            return  result;
        }
    }

    /**
     * 文件导出
     *
     * @param examId   考核任务id
     * @param request
     * @param response
     */
    public void export(String examId,  HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 查询所有机构
        ExamUnitNameDto examUnitNameDto = new ExamUnitNameDto();
        examUnitNameDto.setExamId(examId);
        List<ExamUnitNameDto> list = dcSupExamSumScoreResultDao.queryUnits(examUnitNameDto);
        if (CollectionUtils.isEmpty(list)){
            return;
        }
        Map<String,List<DcSupExamSumQuotaInfo>> result =new LinkedHashMap<>();
        for (int i = 0; i < list.size(); i++) {
             ExamUnitNameDto nameDto = list.get(i);
            List<DcSupExamSumQuotaInfo> quotaInfos = queryExamSumScore(examId,null,nameDto.getExameOrg(),"single");
            List<DcSupExamQuotaAdd> dcSupExamQuotaAdds=queryExamSumScore(examId, null,nameDto.getExameOrg(),"addAndSub");

            if (CollectionUtils.isEmpty(quotaInfos)){
                quotaInfos =new ArrayList<>();
            }

            for (int j = 0; j < dcSupExamQuotaAdds.size(); j++) {
                 DcSupExamQuotaAdd add = dcSupExamQuotaAdds.get(j);

                DcSupExamSumQuotaInfo newInfo =new DcSupExamSumQuotaInfo();
                newInfo.setQuotaType(add.getQuotaType());
                newInfo.setQuotaContent(add.getQuotaContent());
                newInfo.setQuotaWeight(add.getQuotaWeight());
                newInfo.setCurrentYaerGoal(add.getCurrentYaerGoal());
                newInfo.setAssessMethod(add.getAssessMethod());
                newInfo.setPercentage(add.getPercentage());
                newInfo.setQuotaScore(add.getQuotaScore());
                newInfo.setRemarks(add.getRemarks());

                quotaInfos.add(newInfo);
            }
            result.put(nameDto.getExameOrgName(),quotaInfos);
        }

        downLoadInfo(result,request,response);
    }


    private void downLoadInfo( Map<String, List<DcSupExamSumQuotaInfo>>  result,HttpServletRequest request, HttpServletResponse response) {
        // 表头字段名定义
        String[] header = { "类别", "序号", "目标内容",  "权数", "本年度目标", "考核方式", "百分比得分", "分数", "备注", "排名"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 单元格样式
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 自动换行
        cellStyle.setWrapText(true);
        // 字体
        Font dataFont = workbook.createFont();
        dataFont.setFontName("宋体");
        // 字体大小
        dataFont.setFontHeightInPoints((short) 11);
        cellStyle.setFont(dataFont);
        try {
            OutputStream out = response.getOutputStream();

            String fileName="文件导出";
            //定义标题以及设置响应头信息
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName+".xls", "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            result.forEach((k,v)->{
                HSSFSheet sheet = workbook.createSheet(k);
                // 创建标题行
                HSSFRow sheetRow = sheet.createRow(0);
                // 行高
                sheetRow.setHeight((short) (30*20));
                for (int i = 0; i < header.length; i++) {
                    if (i == 2){
                        // 设置宽度
                        sheet.setColumnWidth(2,60*256);
                    }else{
                        sheet.setColumnWidth(i,16*256);
                    }
                    HSSFCell cell = sheetRow.createCell(i);
                    cell.setCellValue(header[i]);
                    cell.setCellStyle(cellStyle);
                }
                // 数据填充
                List<DcSupExamSumQuotaInfo> quotaDataDtoList = v;

                for (int i = 0; i < quotaDataDtoList.size(); i++) {
                    HSSFRow row = sheet.createRow(i + 1);
                    // 设置行高
                    row.setHeight((short) (28*20));
                    DcSupExamSumQuotaInfo quotaDataDto = quotaDataDtoList.get(i);

                    // 指标类别 暂未处理
                    HSSFCell cell2 = row.createCell(0);
                    cell2.setCellStyle(cellStyle);
                    DictData dc_quotaType = DictUtils.getDictData("dc_quotaType", quotaDataDto.getQuotaType());
                    if (dc_quotaType !=null && dc_quotaType.getDictLabel() !=null){
                        cell2.setCellValue(dc_quotaType.getDictLabel());
                    }
                    // 序号
                    HSSFCell cell3 = row.createCell(1);
                    int sort = i+1;
                    cell3.setCellValue(new Long(sort));
                    cell3.setCellStyle(cellStyle);
                    // 目标内容
                    HSSFCell cell4 = row.createCell(2);
                    cell4.setCellValue(quotaDataDto.getQuotaContent()==null?"":quotaDataDto.getQuotaContent());
                    cell4.setCellStyle(cellStyle);
                    // 权数
                    HSSFCell cell6 = row.createCell(3);
                    if (quotaDataDto.getQuotaWeight() !=null){
                        cell6.setCellValue(quotaDataDto.getQuotaWeight());
                    }
                    cell6.setCellStyle(cellStyle);
                    // 本年度目标
                    HSSFCell cell7 = row.createCell(4);
                    cell7.setCellValue(quotaDataDto.getCurrentYaerGoal()==null?"":quotaDataDto.getCurrentYaerGoal());
                    cell7.setCellStyle(cellStyle);
                    // 考核方式 待定
                    HSSFCell cell8 = row.createCell(5);
                    DictData assessment = DictUtils.getDictData("dc_exam_assessment", quotaDataDto.getAssessMethod());
                    if (assessment != null && assessment.getDictLabel() != null) {
                        cell8.setCellValue(assessment.getDictLabel());
                    }
                    cell8.setCellStyle(cellStyle);
                    // 百分比得分
                    HSSFCell cell9 = row.createCell(6);
                    if (quotaDataDto.getPercentage() != null){
                        cell9.setCellValue(quotaDataDto.getPercentage()+"%");
                    }
                    cell9.setCellStyle(cellStyle);
                    // 分数
                    HSSFCell cell10 = row.createCell(7);
                    if (quotaDataDto.getQuotaScore() != null){
                        cell10.setCellValue(quotaDataDto.getQuotaScore());
                    }
                    cell10.setCellStyle(cellStyle);
                    // 备注
                    HSSFCell cell11 = row.createCell(8);
                    DictData remarks = DictUtils.getDictData("dc_exam_remarks", quotaDataDto.getRemarks());
                    if (remarks != null && remarks.getDictLabel() != null){
                        cell11.setCellValue(remarks.getDictLabel());
                    }
                    cell11.setCellStyle(cellStyle);
                    // 排名
                    HSSFCell cell12 = row.createCell(9);
                    cell12.setCellValue(quotaDataDto.getRanking()==null?"":quotaDataDto.getRanking());
                    cell12.setCellStyle(cellStyle);
                }
            });

            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *
     * @param type 站内信  短信
     * @param title 消息标题
     * @return
     */
    private String sendMessage(String type,String title){
        String content="请贵单位抓紧落实【%s】该项任务,并及时给予反馈。";
        MsgPush msgPush =new MsgPush();
        // 消息类型
//        msgPush.setMsgType("");
        // 消息标题
        msgPush.setMsgTitle("督办事项催办");
        // 消息内容
        msgPush.setMsgContent(String.format(content,"关于报送2021年度市政府目标考核单项指标的通知"));
        // 业务类型
        msgPush.setBizType("sms");

        // 接受者姓名
        msgPush.setReceiveUserName("测试");
        // 接受者code
        msgPush.setReceiveUserCode("123456");
        // 接受者账号
        msgPush.setReceiveCode("15377083679");

        // 发送者信息
        msgPush.setSendUserCode("system");
        msgPush.setSendUserCode("123455");

        // 发送时间
        msgPush.setSendDate(new Date());


        smsSendService.sendMessage(msgPush);

        return "发送成功";
    }

    public String message(String title,String contentLevel,String contentType,String msgContent,String orgCode ,String orgName){
//        MsgInner msgInner =new MsgInner();
//        msgInner.setMsgTitle("督办事项催办");
//        msgInner.setContentLevel(MsgInner.CONTENT_LEVEL_1);
//        msgInner.setContentType(MsgInner.RECEIVE_TYPE_POST);
//        msgInner.setMsgContent(" 请贵单位抓紧落实【关于报送2021年度市政府目标考核单项指标的通知】该项任务，并及时给予反馈");
//        // 个人的话取 user_code
//        msgInner.setReceiveCodes("xhc001_3n6f");
//        msgInner.setReceiveNames("帅帅晨");
//        msgInner.setStatus(MsgInner.RECEIVE_TYPE_USER);
//        msgInner.setReceiveType(MsgInner.RECEIVE_TYPE_USER);
//        msgInner.setNotifyTypes("PC");
//        msgInner.setStatus("0");
//        msgInnerService.save(msgInner);
        return "发送成功";
    }






}
